namespace Maple.Branch.Permissions.DataSeed
{
    using System.Linq;
    using System.Threading.Tasks;
    using Volo.Abp.Authorization.Permissions;
    using Volo.Abp.Data;
    using Volo.Abp.DependencyInjection;
    using Volo.Abp.MultiTenancy;

    public class PermissionsDataSeedContributor : IDataSeedContributor, ITransientDependency
    {
        protected ICurrentTenant CurrentTenant { get; }

        protected IPermissionDefinitionManager PermissionDefinitionManager { get; }
        protected IPermissionsDataSeeder DataSeeder { get; }

        public PermissionsDataSeedContributor(
            IPermissionDefinitionManager permissionDefinitionManager,
            IPermissionsDataSeeder dataSeeder,
            ICurrentTenant currentTenant)
        {
            PermissionDefinitionManager = permissionDefinitionManager;
            DataSeeder = dataSeeder;
            CurrentTenant = currentTenant;
        }

        public virtual Task SeedAsync(DataSeedContext context)
        {
            var multiTenancySide = CurrentTenant.GetMultiTenancySide();
            var permissionNames = PermissionDefinitionManager
                .GetPermissions()
                .Where(p => p.MultiTenancySide.HasFlag(multiTenancySide))
                .Select(p => p.Name)
                .ToArray();

            return DataSeeder.SeedAsync(
                RolePermissionValueProvider.ProviderName,
                "admin",
                permissionNames,
                context.TenantId
            );
        }
    }
}
